import { AxiosHeaders, AxiosResponseHeaders, RawAxiosResponseHeaders } from "axios";
export namespace ContentDisposition {
  export type Data = {
    type: 'attachment' | 'inline' | string;
    parameters: { [key: string]: string | undefined };
  }
  export async function parse(headersOrRawStr: string | RawAxiosResponseHeaders | AxiosResponseHeaders): Promise<Data> {
    const rawStr = typeof headersOrRawStr === 'string' ?
      headersOrRawStr :
      headersOrRawStr instanceof AxiosHeaders ?
        headersOrRawStr.get('content-disposition') :
        headersOrRawStr['content-disposition'];
    if (typeof rawStr !== 'string') {
      throw new Error('无法获取content-disposition, 请确定返回数据头中已正确的设置Access-Control-Expose-Headers');
    }
    const ret: Data = {
      type: '',
      parameters: {}
    }
    if (typeof rawStr === 'string') {
      const parts = rawStr.split(';')
        .map(v => v.trim())
        .filter(v => v);
      ret.type = parts[0];
      const len = parts.length
      for (let i = 1; i < len; ++i) {
        const result = parts[i].match(/(.*?)=(.*?)$/)
        if (!result) { continue; }

        if (result[1] === 'filename*') {
          const valueResult = result[2].match(/(.*)'(.*)'(.*)/)
          if (!valueResult) { continue; }
          ret.parameters['charset'] = valueResult[1];
          ret.parameters['lang'] = valueResult[2];
          ret.parameters['fileName'] = decodeURI(valueResult[3]);
          continue;
        }
        ret.parameters[result[1]] = result[2];
      }
    }
    return ret;
  }
}
